package org.weso.lodin.appserv;

import java.io.PrintWriter;
import java.util.List;

import org.apache.log4j.Logger;
import org.weso.lodin.analyzer.CountryReconciliator;
import org.weso.lodin.dao.CountryDAO;
import org.weso.lodin.to.CountryTO;
import org.weso.lodin.to.ObservationTO;
import org.weso.lodin.to.ScoreTO;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;

public class ScoreAppServ {



	private CountryDAO daoCountries;




	public ScoreAppServ(CountryDAO daoCountries){
		this.daoCountries = daoCountries;
	}

	protected static Logger logger = Logger.getLogger(ScoreAppServ.class);
	//FIXME
	public int generateModel (List<ScoreTO> scores, PrintWriter writer, int init){
		int obs = init;
		decorateCountries(daoCountries, scores);
		for(ScoreTO scoreTO:scores){
			writer.println("wi-score:s"+obs+"  a   qb:Observation;");
			writer.println("\trdfs:label"+"\t\""+scoreTO.getRef()+" score of "+scoreTO.getCountry()+" in 2011"+"\"@en;");
			writer.println("\twi-onto:ref-area"+"\twi-country:"+scoreTO.getCountryDecorated().getCode()+";");
			writer.println("\twi-onto:ref-sheet"+"\twi-onto:Score;");
			writer.println("\twi-onto:ref-type"+"\twi-indicator:"+scoreTO.getRef()+";");
			writer.println("\twi-onto:ref-year \t \"2011\"^^xsd:int;");
			writer.println("\tdcterms:date \t \"2011\"^^xsd:int;");
			writer.println("\twi-onto:ref-value"+"\t\""+scoreTO.getValue()+"\"^^xsd:double;");
			writer.println("\tdcterms:contributor wi-org:WESO ;");
			writer.println("\tdcterms:publisher wi-org:WebFoundation ;");
			writer.println("\tqb:dataSet wi-dataset-score:"+scoreTO.getRef()+";");
			writer.println("\tsdmx-concept:obsStatus  sdmx-code:obsStatus-A .");
			obs++;
		}
		writer.close();
		return obs;
              
	}

	protected static void decorateCountries(CountryDAO daoCountries, List<ScoreTO> scores){
		List<CountryTO> countries = daoCountries.getCountries();
		CountryReconciliator reconciliatorCountry = new CountryReconciliator(countries);	
	    for(ScoreTO observation:scores){
	    	List<CountryTO> results = reconciliatorCountry.search(observation);
	    	if(results.size()>0){
	    		CountryTO match = results.get(0);
	    		//logger.debug("Match for country name "+observation.getCountry()+" found "+match.getName());	    		
	    		observation.setCountryDecorated(match);
	    	}else{
	    		logger.warn("No match country for observation "+observation);
	    	}	    	
	    }	    	
	  }

}
